﻿using System;
using System.Windows.Threading;
using XamlingCore.Infrastructure.Dialog;
using XamlingCore.Infrastructure.View.Implementation;

namespace XamlingCore.Infrastructure.View.DialogView
{
    public class DialogViewModelBase : ViewModelBase 
    {
        private object currentDialogObject;

        public new virtual void ShowDialog(ShowDialogViewModelBase dialogViewModel, TimeSpan timeOut, Action<DialogResult> dialogResult)
        {
            CurrentDialogObject = dialogViewModel;
            dialogViewModel.DialogComplete = dialogResult;
            dialogViewModel.CloseDialog = () =>
            {
                if (CurrentDialogObject == dialogViewModel)
                {
                    HideDialog();
                }
            };

            SetActive(CurrentDialogObject, true);

            if (timeOut != TimeSpan.Zero)
            {
                dialogViewModel.DialogTimeOut = timeOut;
                DispatcherTimer t = new DispatcherTimer();

                t.Interval = timeOut;

                t.Tick += (s, e) =>
                {
                    t.Stop();
                    t = null;

                    if (CurrentDialogObject == dialogViewModel)
                    {
                        HideDialog();
                    }
                };
                t.Start();
            }
        }

        public void ShowDialog(ShowDialogViewModelBase dialogViewModel, Action<DialogResult> dialogResult)
        {
            ShowDialog(dialogViewModel, TimeSpan.Zero, dialogResult);
        }

        public void ShowDialog(ShowDialogViewModelBase dialogViewModel)
        {
            ShowDialog(dialogViewModel, TimeSpan.Zero, null);
        }

        public virtual void HideDialog()
        {
            if (CurrentDialogObject != null)
            {
                SetActive(CurrentDialogObject, false);
            }
            CurrentDialogObject = null;
        }

        public object CurrentDialogObject
        {
            get { return currentDialogObject; }
            set
            {
                currentDialogObject = value;
                OnPropertyChanged("CurrentDialogObject");
            }
        }
    }
}
